<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入用户名" 
            clearable 
            @clear="handleInputChange"
            @input="handleInputChange"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input 
            v-model="searchForm.email" 
            placeholder="请输入邮箱" 
            clearable 
            @clear="handleInputChange"
            @input="handleInputChange"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="searchLoading">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户表格 -->
    <div class="table-container">
      <el-table :data="tableData" v-loading="loading" border stripe :table-layout="'auto'">
        <el-table-column prop="id" label="ID" width="50" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="avatar" label="头像" width="60">
          <template #default="{ row }">
            <el-avatar :size="32">
              <img
                :src="getAvatarUrl(row.avatar) || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="200" show-overflow-tooltip />
        <el-table-column label="角色" min-width="120">
          <template #default="{ row }">
            <el-tag v-for="u in row.roles" :key="u.id" class="role-tag" size="small" :type="getRoleTagType(u.name)">
              {{ u.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="120" align="center">
          <template #default="{ row }">
            <div class="status-control">
              <el-switch v-model="row.isActive" :active-value="true" :inactive-value="false"
                @change="handleToggleStatus(row)" />
              <span class="status-text">
                {{ row.isActive ? '启用' : '禁用' }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="修改时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleEdit(row)" icon="Edit">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handlePageChange" />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" :before-close="handleCloseDialog">
      <el-form ref="userForm" :model="userFormData" :rules="userFormRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userFormData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userFormData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="userFormData.roleIds" placeholder="请选择角色" style="width: 100%" multiple>
            <el-option v-for="role in availableRoles" :key="role.id" :label="role.name" :value="role.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { usernameRules, passwordRules, emailRules } from '@/utils/validationRules'
import { useRoleStore } from '@/stores/role'
// 响应式数据
const loading = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const currentUser = ref(null)
const userForm = ref()
const useAuthStore = useUserStore();
const useroleStore = useRoleStore();
const searchLoading = ref(false) // 搜索加载状态
let searchTimer = null; // 搜索防抖定时器
// 搜索表单
const searchForm = reactive({
  username: '',
  email: ''
})

// 分页数据
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 用户表单数据
const userFormData = reactive({
  userid: null,
  username: '',
  email: '',
  phone: '',
  roleIds: []
})

// 可用角色
const availableRoles = ref([])
const loadRoles = async () => {
  try {
    // 模拟API调用获取角色列表
    const response = await useroleStore.getRoles();
    await new Promise(resolve => setTimeout(resolve, 300))
    console.log(response.roles);

    availableRoles.value = response.roles; // 后端返回的角色列表在 response 中
    // 实际情况下这里应该是API请求
    console.log('角色列表加载完成')
  } catch (error) {
    console.error('加载角色列表失败:', error);
    ElMessage.error('加载角色列表失败')
  }
}
// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑用户' : '新增用户')

// 表单验证规则
const userFormRules = {
  username: usernameRules,
  email: emailRules,
  password: passwordRules,
  roleIds: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}
const getAvatarUrl = (avatar) => {
  console.log('AdminLayout - 原始头像路径:', avatar)

  if (!avatar) {
    console.log('AdminLayout - 没有头像，返回空字符串')
    return ''
  }

  // 如果已经是完整URL，直接返回
  if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
    console.log('AdminLayout - 完整URL，直接返回:', avatar)
    return avatar
  }

  // 如果是相对路径，加上后端基础URL
  const baseUrl = 'http://admin-lusiyi.ijelly.cn'
  let fullUrl
  if (avatar.startsWith('/')) {
    fullUrl = baseUrl + avatar
  } else {
    fullUrl = baseUrl + '/' + avatar
  }

  console.log('AdminLayout - 构建的完整URL:', fullUrl)
  return fullUrl
}
// 方法
const loadData = async (searchParams = {}) => {
  loading.value = true;
  try {
    let response;
    
    // 检查是否有搜索参数
    const hasSearchParams = searchParams.username?.trim() || searchParams.email?.trim();
    
    if (hasSearchParams) {
      // 使用搜索API
      response = await useAuthStore.searchUsers(
        searchParams, 
        {
          page: pagination.value.page,
          pageSize: pagination.value.pageSize
        }
      );
    } else {
      // 使用普通的用户列表API
      response = await useAuthStore.userslist({
        page: pagination.value.page,
        pageSize: pagination.value.pageSize
      });
    }
    
    console.log('API响应:', response);
    
    // 更新表格数据和分页信息
    tableData.value = response.users || [];
    pagination.value = response.pagination;

  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('加载数据失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
}
//搜索查询
const handleSearch = async () => {
  console.log('开始搜索，参数:', searchForm);
  searchLoading.value = true;
  
  // 重置到第一页
  pagination.value.page = 1;
  
  try {
    // 调用 loadData 并传入搜索参数
    await loadData({
      username: searchForm.username,
      email: searchForm.email
    });
    
    if (tableData.value.length > 0) {
      ElMessage.success(`搜索完成，找到 ${pagination.value.total} 条记录`);
    } else {
      ElMessage.info('未找到匹配的用户');
    }
  } catch (error) {
    console.error('搜索失败:', error);
    ElMessage.error('搜索失败');
  } finally {
    searchLoading.value = false;
  }
}

// 处理输入变化（防抖搜索）
const handleInputChange = () => {
  // 清除之前的定时器
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  
  // 设置新的定时器，500ms后执行搜索（不显示提示消息）
  searchTimer = setTimeout(() => {
    handleSearchSilent();
  }, 500);
};

// 静默搜索（不显示提示消息）
const handleSearchSilent = async () => {
  console.log('开始静默搜索，参数:', searchForm);
  
  // 重置到第一页
  pagination.value.page = 1;
  
  try {
    // 调用 loadData 并传入搜索参数
    await loadData({
      username: searchForm.username,
      email: searchForm.email
    });
  } catch (error) {
    console.error('搜索失败:', error);
  }
};

const handleReset = () => {
  // 清除防抖定时器
  if (searchTimer) {
    clearTimeout(searchTimer);
    searchTimer = null;
  }
  
  Object.assign(searchForm, {
    username: '',
    email: ''
  })
  pagination.value.page = 1;
  loadData()
  ElMessage.success('搜索条件已重置');
}
//点击编辑按钮获取该表单数据
const handleEdit = (row) => {
  isEdit.value = true
  currentUser.value = row
  console.log(currentUser.value);

  Object.assign(userFormData, {
    userid: row.id,
    isActive: row.isActive,
    username: row.username,
    email: row.email,
    roleIds: row.roles.map(role => role.id)
  })
  dialogVisible.value = true
}

//删除用户√
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.username}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // API调用
    const response = await useAuthStore.deleteuser(row.id)
    if (response.code !== 200) {
      throw new Error(response.message || '删除失败')
    }
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('删除成功')
    loadData({
      username: searchForm.username,
      email: searchForm.email
    })
  } catch {
    // 用户取消操作或删除失败
  }
}
//状态切换-修改用户信息√ o(*￣▽￣*)ブ
const handleToggleStatus = async (row) => {
  const action = row.isActive ? '启用' : '禁用'
  try {
    await useAuthStore.updateUser(row.id, {
      username: row.username,
      email: row.email,
      isActive: row.isActive,
      roleIds: row.roles.map(role => role.id)
    })
    await new Promise(resolve => setTimeout(resolve, 300))
    ElMessage.success(`${action}成功`)
  } catch {
    // 如果操作失败，还原开关状态
    row.isActive = !row.isActive
    ElMessage.error(`${action}失败`)
  }
}
//编辑用户信息√
const handleSubmit = async () => {
  if (!userForm.value) return

  try {
    await userForm.value.validate()
    submitLoading.value = true
    // 编辑用户信息API调用
    await useAuthStore.updateUser(userFormData.userid, {
      username: userFormData.username,
      email: userFormData.email,
      isActive: userFormData.isActive,
      roleIds: userFormData.roleIds
    });

    await new Promise(resolve => setTimeout(resolve, 1000))

    ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
    dialogVisible.value = false
    loadData({
      username: searchForm.username,
      email: searchForm.email
    })
  } catch {
    // 表单验证失败
  } finally {
    submitLoading.value = false
  }
}

const handleCloseDialog = () => {
  dialogVisible.value = false
  resetFormData()
  if (userForm.value) {
    userForm.value.resetFields()
  }
}

const resetFormData = () => {
  Object.assign(userFormData, {
    username: '',
    email: '',
    roleIds: []
  })
}

const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.page = 1
  loadData({
    username: searchForm.username,
    email: searchForm.email
  })
}

const handlePageChange = (val) => {
  pagination.value.page = val
  loadData({
    username: searchForm.username,
    email: searchForm.email
  })
}
// 格式化时间函数
const formatDate = (time) => {
  if (!time) return '';
  const date = new Date(time);
  const beijingTime = new Date(date.getTime() + 8 * 3600 * 1000); // 转换为北京时间
  return beijingTime.toISOString().replace('T', ' ').substring(0, 19); // 格式化为 YYYY-MM-DD HH:MM:SS
};

const getRoleTagType = (role) => {
  const roleTypeMap = {
    'SuperAdmin': 'danger',
    'Admin': 'warning',
    'User': 'primary'
  }
  return roleTypeMap[role] || 'info'
}

// 生命周期
onMounted(() => {
  loadData()
  loadRoles()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.search-bar {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.role-tag {
  margin-right: 4px;
}

.status-control {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.status-text {
  font-size: 12px;
  color: #606266;
  min-width: 24px;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}
</style>